package de.recipeminer.persistence;

import com.db4o.Db4oEmbedded;
import com.db4o.config.EmbeddedConfiguration;
import de.recipeminer.tools.Config;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.IOException;

/**
 * Simple data carrier class to specify the settings for Db4o Embedded databases
 * used in this project.
 *
 * @author Markus Ackermann
 */
public abstract class Db4oDescriptor{
    private static Logger logger = Logger.getLogger(Db4oDescriptor.class);
    public abstract File getRelaticeDbFile();
    public abstract EmbeddedConfigurationProvider getConfigurationProvider();

    public File getDbFile() {
        try {
            return getRelaticeDbFile().getCanonicalFile();
        } catch (IOException e) {
            String msg = String.format("Error resolving canocical path of database file %s, using unresolved path.",
                    getRelaticeDbFile().getPath());
            logger.error(msg, e);
            return getRelaticeDbFile();
        }
    }

    public static Db4oDescriptor DEFAULT = new Db4oDescriptor() {
        @Override
        public File getRelaticeDbFile() {
            return Config.getInstance().getResourceFile("recipeminer.db4o", true);
        }

        @Override
        public EmbeddedConfigurationProvider getConfigurationProvider() {
            return new DefaultConfigurationProvider();
        }
    };

    public static Db4oDescriptor TEST = new Db4oDescriptor() {
        @Override
        public File getRelaticeDbFile() {
            return Config.getInstance().getResourceFile("test/recipeminer.db4o", false);
        }

        @Override
        public EmbeddedConfigurationProvider getConfigurationProvider() {
            return new DefaultConfigurationProvider();
        }
    };

    public static Db4oDescriptor CLEARABLE = new Db4oDescriptor() {
        @Override
        public File getRelaticeDbFile() {
            return Config.getInstance().getResourceFile("test/clearable.db4o", false);
        }

        @Override
        public EmbeddedConfigurationProvider getConfigurationProvider() {
            return new DefaultConfigurationProvider();
        }
    };

    interface EmbeddedConfigurationProvider {
        public EmbeddedConfiguration getConfig();
    }

    public static class DefaultConfigurationProvider implements EmbeddedConfigurationProvider {
        public EmbeddedConfiguration getConfig() {
            EmbeddedConfiguration config = new Db4oEmbedded().newConfiguration();
            config.common().activationDepth(Integer.MAX_VALUE);
            config.common().updateDepth(Integer.MAX_VALUE);
            return config;
        }
    }
}
